package br.com.iswe.gwt.ui.client;

import com.google.gwt.user.client.ui.TextBox;

public class MaxNumberValidator extends BaseValidator {

	private Double maxValue = 0d;
	
	public MaxNumberValidator(String nome, String label, Object item, Double maxValue) {
		super(nome,label, item);
		this.maxValue = maxValue;
	}


	public MaxNumberValidator(String label, Double maxValue) {
		//
		super(label);
		this.maxValue = maxValue;
	}


	public boolean validateImpl() {
		//verifica o tipo de objeto
		if(item instanceof TextBox){
			return validate((TextBox)item);
		}
		if(item instanceof LookUp){
			return validate(((LookUp)item).getIdTextBox());
		}
		//caso nao reconhece o objeto
		return false;
	}
	
	public boolean validate(TextBox box) {
		if( isEmpty( box.getText() )){
			return true;
		}
		//verifica se o campo esta preenchido
		if(! isEmpty( box.getText() ) && isInLimit(box.getText()) ){
			valid(box);
			return true;
		}
		notValid(box, commonMessages.msgValorMaximoExedido(label, maxValue + ""));
		return false;
	}


	private boolean isInLimit(String text) {
		boolean result = false;
		//verifica se e numero
		try{
			Double valor = Double.parseDouble(text);
			if(valor.doubleValue() <= maxValue.doubleValue()){
				result = true;
			}
		}
		catch (Exception e) {
			//nao e valido
			result = false;
		}
		
		
		return result;
	}
}
